package com.example.thirdhomework

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class FifthActivity() : AppCompatActivity() {
    var seconds = 0
    var running = false
    var wasRunning = false
    private lateinit var textTime: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_fifth)

       textTime = findViewById(R.id.textView_time)

        if (savedInstanceState != null) {
            seconds = savedInstanceState.getInt("seconds")
           running = savedInstanceState.getBoolean("running")
           wasRunning = savedInstanceState.getBoolean("wasRunning")
       }
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
       runTimer()

       val buttonStart = findViewById<Button>(R.id.button_start)
       buttonStart.setOnClickListener {
            running = true
        }
      val buttonStop = findViewById<Button>(R.id.button_stop)
       buttonStop.setOnClickListener {
           running = false
       }

       val buttonReset = findViewById<Button>(R.id.button_reset)
      buttonReset.setOnClickListener {
           running = false
           seconds = 0
      }
    }
  private fun runTimer() {
      val handler = Handler(Looper.getMainLooper())
      val runnable = object : Runnable {
           @SuppressLint("DefaultLocale")
           override fun run() {
                val hours = seconds / 3600
                val minutes = seconds % 3600 / 60
                val secs = seconds % 60
                val time = String.format("%d:%02d:%02d", hours, minutes, secs)
                textTime.text = time
                if(running) {
                    seconds++
                }
                handler.postDelayed(this, 1000)
            }
        }
        handler.post(runnable)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("seconds", seconds)
        outState.putBoolean("running", running)
        outState.putBoolean("wasRunning", wasRunning)
    }
}
